package com.ansion.commonchat.contact;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.helper.ContactsHelper;
import com.ansion.basedb.dao.model.ContactsModel;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.commonchat.contact.sync.SyncContactsManager;
import com.ansion.commonchat.contact.systemcontact.AndroidContactDB;
import com.ansion.commonchat.contact.systemcontact.AndroidContactPhoneBean;
import com.ansion.commonchat.contact.systemcontact.AndroidContactsFactory;
import com.ansion.commonchat.contact.utils.GetMatchUserManager;
import com.ansion.commonchat.util.FormatUserIdHelper;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.utils.CocoLocalBroadcastUtil;
import com.ansion.utils.thread.AbstractRefreshUIThread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class ContactsLoadManager {
	private static ContactsLoadManager manager;
	private boolean isFirstLoad = true;
	private AbstractRefreshUIThread thread = new AbstractRefreshUIThread() {

		@Override
		protected boolean loadUIData() {
			VLog.d("ContactLoadReceiver", "loadUIData");
			loadUser();
			return true;
		}

	};

	private ContactsLoadManager() {
		thread.setRefreshInterval(2000);
		registerReceiver();
//		if (!Build.BRAND.equalsIgnoreCase("Meizu")) {
			SyncContactsManager.getInstance().registerContactsChange();
//		}
	}

	public static ContactsLoadManager getInstance() {
		if (null == manager) {
			manager = new ContactsLoadManager();
		}
		return manager;
	}

	private void registerReceiver() {
		ContactLoadReceiver receiver = new ContactLoadReceiver();
		
		IntentFilter filter=new IntentFilter();
		filter.addAction(BConstant.FriendAction.ACTION_READCONTACT_END);
		filter.addAction(AppConstants.FriendShipAction.ACTION_GETMATCHUSERS_END);
		CocoLocalBroadcastUtil.registerLocalBroadCast(receiver,filter);
	}

	class ContactLoadReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			loadLocalContacts();
		}

	}

	public void loadLocalContacts() {
		
			thread.startQuery();
	}

	private void loadUser() {

		VLog.d("ContactLoadReceiver", "loadUser start");
		CurrentUser user = LoginedUserMgr.getCurrentLoginedUser();
		if (null == user) {
			VLog.i("ContactLoadReceiver", "null");
			return;
		}
		
//		if(GetMatchUserManager.isFirstMatched()==false){
//			VLog.e("ContactLoadReceiver", "GetMatchUserManager.isFirstMatched()==false");
//			return;
//		}
		
		// if (AndroidContactsFactory.hasLoadEnd()) {
		
		HashSet<AndroidContactDB> allContacts = AndroidContactsFactory
				.getAllContactsSet();
		VLog.d("ContactLoadReceiver", "allContacts size:" + (allContacts == null ? 0 : allContacts.size()));
		//第三方权限禁止soma访问联系人，会导致读到的系统通讯录为空。所以，当读到系统通讯录为空时，不同步到soma数据库
		if (null != allContacts&&allContacts.isEmpty()==false) {
			// List<UserModel> userList = new ArrayList<UserModel>();
			Map<Long, ContactsModel> map = new HashMap<Long, ContactsModel>();
			ContactsModel contactsModel;
			Iterator<AndroidContactDB> it = allContacts.iterator();
			while (it.hasNext()) {
				AndroidContactDB db = it.next();
				if (null != db.getPhoneBeanMap()) {
					for (AndroidContactPhoneBean phoneBean : db
							.getPhoneBeanMap().values()) {
//						long id = PhoneNumberHelper.getNumberWithCountryCode(
//								Integer.parseInt(user.getCountry()),
//								phoneBean.getPhone());
						
						long id= FormatUserIdHelper.getFormatUserid(Integer.parseInt(user.getCountry()), phoneBean.getPhoneOriginal());
						if (0 != id && id != user.getUserId()) {
							contactsModel = new ContactsModel();
							contactsModel.setUserId(id);
							contactsModel.setContactId(db.getId());
							contactsModel.setFirstName(db.getFirstName());
							contactsModel.setLastName(db.getLastName());
							contactsModel.setMiddleName(db.getMiddleName());
							contactsModel.setHasAvatarInLocalAddress(db
									.avatarAvailable());
							if (map.get(id) == null
									|| AndroidContactsFactory
											.getContactIdIndex(map.get(id)
													.getContactId()) > AndroidContactsFactory
											.getContactIdIndex(contactsModel
													.getContactId())) {
								map.put(id, contactsModel);
							}
						}
					}
				}
			}
			List<ContactsModel> userList = new ArrayList<ContactsModel>();
			for (ContactsModel model : map.values()) {
				userList.add(model);
			}
			// UserHelper.saveSimpleUsers(userList);
			VLog.d("ContactLoadReceiver", "checkAllContacts start");
			ContactsHelper.checkAllContacts(userList,isFirstLoad);
//			SessionLoadManager.getInstance().init();
			// }
//			ImageViewEx.clearContactsAvatarCache();
			allContacts.clear();
			allContacts = null;	
		}
		VLog.d("ContactLoadReceiver", "loadUser end");
		ContactsHelper.setContactLoaded();
		CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
				BConstant.Contact.ACTION_LOADCONTACTS_END));
		isFirstLoad = false;
	}

	// public static int getAllPhoneCount(Map<Integer, AndroidContactDB>
	// allContacts){
	// int i=0;
	// if (null != allContacts) {
	// for (AndroidContactDB db : allContacts.values()) {
	// if (null != db.getPhoneBeanMap()) {
	// for (AndroidContactPhoneBean phoneBean : db
	// .getPhoneBeanMap().values()) {
	// i++;
	// }
	// }
	// }
	// }
	// return i;
	// }
	
	public void clear(){
		isFirstLoad = true;
	}
}
